#!/usr/bin/python
# -*- coding: UTF-8 -*-

# 自动报表


import os
from openpyxl import load_workbook
import shutil
from auto_report.auto_report import AutoReport

from auto_report.utils import info, warning, read_from_xlsx, get_font
from openpyxl.utils.cell import coordinate_from_string


XIAN_VALUE_MAP = {
    '华宁县': 'A5:T6',
    '峨山县': 'A7:T8',
}

TARGET_AREA = 'A5:T8'
MOD_START = 2
MOD_END = 19

TEXT_BLACK_10 = get_font('000000', 10)
TEXT_RED_10 = get_font('ff0000', 10)


class NotLakeReport(AutoReport):
    def __init__(self, target_month):
        super(NotLakeReport, self).__init__(target_month)
        self.target_month = target_month
        self.report_name = '附件2：重点流域（除九湖外）治理项目调度表'

    def get_src_file(self):
        return f'玉溪市-{self.get_last_month_field()}-{self.report_name}.xlsx'

    def get_dst_file(self):
        return f'玉溪市-{self.get_month_field()}-{self.report_name}.xlsx'

    # def sumary(self):
    #     wb = load_workbook(self.dst_file, data_only=True)
    #     ws = wb.active

    #     total = wanToYi(ws['C4'].value)
    #     total2019 = wanToYi(ws['K4'].value)
    #     current2020 = wanToYi(ws['N4'].value)
    #     sumaryStr = f'总投资{total}亿元。截止2019年完成投资{total2019}亿元，2020年完成投资{current2020}亿元。'
    #     print('汇总', sumaryStr)

    def generate(self):
        src_file = self.get_src_file() if os.path.exists(
            self.get_src_file()) else f'{self.report_name}.xlsx'

        wb = load_workbook(src_file)
        ws = wb.active

        src_folder = f'feijiu/{self.target_month}'
        files = self.get_files(src_folder)
        for f in files:
            data = read_from_xlsx(f'{src_folder}/{f}', row_offset=4)
            if not type(data[0][0]) == int:
                continue
            print('处理', f)

            mod_data = ws['A5:T8']

            for i, r in enumerate(mod_data):
                for j in data:
                    if r[1].value == j[1]:
                        for k in range(2, 19):
                            if r[k].value != j[k]:
                                newVal = j[k]
                                print(
                                    f'修改 {r[k].coordinate}, {r[k].value} -> {newVal}')
                                r[k].value = newVal
                                r[k].font = TEXT_RED_10
                            else:
                                r[k].font = TEXT_BLACK_10


        ws['A1'].value = f'重点流域（除九湖外）治理项目投资完成情况表（{self.get_month_field()}）'
        dst_file = self.get_dst_file()
        wb.save(dst_file)

        print('完成', dst_file)

    def split(self):
        split_file = self.get_dst_file() if os.path.exists(
            self.get_dst_file()) else None
        if (split_file == None):
            warning('错误！找不到文件', split_file)
            return
        info('拆分', split_file)
        target_dir = 'dst'
        if os.path.exists(target_dir):
            shutil.rmtree(target_dir)
        os.mkdir(target_dir)

        from_wb = load_workbook(split_file)
        all_row_start = coordinate_from_string(
            TARGET_AREA.split(':')[0])[1]  # 4
        all_row_end = coordinate_from_string(
            TARGET_AREA.split(':')[1])[1]  # 8
        info('all row', all_row_start, all_row_end)
        lakes = set(XIAN_VALUE_MAP.keys())
        for index, key in enumerate(lakes):
            one_xian_file = f'{target_dir}/{index}-{key}-{self.get_month_field()}-{self.report_name}.xlsx'
            from_wb.save(one_xian_file)

            start_row = coordinate_from_string(
                XIAN_VALUE_MAP.get(key).split(':')[0])[1]
            end_row = coordinate_from_string(
                XIAN_VALUE_MAP.get(key).split(':')[1])[1]
            info(start_row, end_row)
            before_range = (all_row_start, start_row-all_row_start)
            after_range = (end_row+1, all_row_end-end_row)
            info(before_range, after_range)

            new_wb = load_workbook(one_xian_file)
            new_ws = new_wb.active

            if after_range[1] > 0:
                new_ws.delete_rows(after_range[0], after_range[1])
            if before_range[1] > 0:
                new_ws.delete_rows(before_range[0], before_range[1])

            new_wb.save(one_xian_file)

            new_wb = load_workbook(one_xian_file)
            new_ws = new_wb.active

            one_lake_mod_area = new_ws[TARGET_AREA]
            for _, r in enumerate(one_lake_mod_area):
                for colIndex in range(MOD_START, MOD_END):
                    r[colIndex].font = TEXT_BLACK_10
            new_wb.save(one_xian_file)

        info('done')


if __name__ == "__main__":
    report = NotLakeReport()
    report.generate()
